/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */
import path from 'path';

import {expect} from '@jest/globals';
import execa from 'execa';
import fse from 'fs-extra';

import {runHvigorAsync} from '../../common/common';
import {PackageJsonModifier} from '../../common/modifier/package-json-modifier';
import {commonConfig} from '../../plugins/common-config';
import {commonJson5Operation, readJson5} from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel, CURRENT_HMOS_API,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import {Project} from '../../plugins/project-builder/models/project-models';
import {ICaseRecord} from '../../plugins/report-builder/report-models';
import {TestCaseBuilder} from '../../plugins/task-builder/task-case-builder';
import {ProjectBuildOption, TestCaseFun} from '../../plugins/task-builder/test-case';
import {TestTaskOption, TestTaskOptionBuilder} from '../../plugins/task-builder/test-task-option';
import {HOS_SIGNATURE_TEMPLATE} from '../../warable-api8/constants';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: CURRENT_HMOS_API,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibrary]: 1,
  },
};

/**
 * 1. 创建一个模版har模块，在oh-package依赖远程hsp
 * 2. 构建Har模块
 * 3. 给har添加签名配置
 * 4. 查看path中有没有output_metadata.json文件
 * path：library\build\default\intermediates\hap_metadata\ohosTest\
 */

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.Sign).ohpmInstall(IsEnable.Enable).build();

const testFun: TestCaseFun = async (project: Project, taskConfig, record: ICaseRecord) => {
  const projectRoot = project.projectRootPath();
  const commands = '--mode module -p module=staticLibrary@ohosTest -p isOhosTest=true -p buildMode=test genOnDeviceTestHap --analyze=normal --debug --parallel --no-incremental --no-daemon'.split(' ');
  const ohPackageModifier = new PackageJsonModifier(projectRoot, 'staticLibrary');
  ohPackageModifier.setDependencies({'inte_rem_hsp100': '1.0.0'}).outputSync();


  await commonJson5Operation(path.resolve(projectRoot, 'build-profile.json5'), async (json5): Promise<void> => {
    json5.app.signingConfigs = [HOS_SIGNATURE_TEMPLATE];
    json5.app.products[0] = {
      'buildOption': {
        'strictMode': {
          'useNormalizedOHMUrl': true
        }
      },
      ...json5.app.products[0]
    };
  });

  const filePath = path.resolve(projectRoot, 'staticLibrary', 'build', 'default', 'intermediates', 'hap_metadata', 'ohosTest', 'output_metadata.json');
  await execa.command(commonConfig.ohpmInstallCommand, {
    cwd: projectRoot
  });
  const result = await runHvigorAsync(projectRoot, commands);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(fse.existsSync(filePath)).toBe(true);
  // 读结果的output_metadata.json文件
  const outPutMetaData =  await readJson5(filePath);
  const outPutMetaDataResult =  outPutMetaData.some((item: any) => item.dependRemoteHsps && item.dependRemoteHsps.length > 0);
  expect(outPutMetaDataResult).toBe(true);
};

TestCaseBuilder.builder()
  .caseName('har_with_remote_hsp')
  .description('har模块依赖远程签名hsp，生成ohosTest的信息')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testFun)
  .load();